import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName TimeMap
 * @Author 真正的小明被占用了
 * @Date 2018/12/16/016 18:51
 * @Version 1.0
 *
 */
public class TimeMap extends org.apache.hadoop.mapreduce.Mapper implements Mapper<Text, Text,Text, LongWritable> {


    public static void main(String[] args) {

    }
    @Override
    public void map(Text text, Text text2, OutputCollector<Text, LongWritable> outputCollector, Reporter reporter) throws IOException {
        String lastTime=text.toString();//上一次的时间
        String line=text2.toString();//当前读取的一行
        String nowTime=line.split(",")[1];
        String V=line.split(",")[4];//速度
        if(!V.equals("0.0")){//速度不为0
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date lastDate=sdf.parse(lastTime);//开始的时间
                Date nowDate=sdf.parse(nowTime);//本行的时间
                long T = lastDate.getTime() - nowDate.getTime();//中间时间差
                String nowWeek=dayForWeek(nowTime.split(" ")[0]);//当前行日期对应的星期
                String nowHour=nowTime.split(" ")[1].split(":")[0];//当前行日期对应的小时
                String outKey=nowWeek+','+nowHour;//得到输出的key值  本行处理好的星期和小时
                outputCollector.collect(new Text(outKey),new LongWritable(T));//得到输出key-value值
            } catch (Throwable e){
                e.printStackTrace();
            }
        }else{//速度为0
            outputCollector.collect(new Text("////"),new LongWritable(0L));//得到输出key-value值
        }
    }

    //获得一个日期的星期几
    public static String dayForWeek(String pTime) throws Throwable {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date tmpDate = format.parse(pTime);
        Calendar cal = Calendar.getInstance();
        String[] weekDays = { "7", "1", "2", "3", "4", "5", "6" };
        try {
            cal.setTime(tmpDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    @Override
    public void close() throws IOException {

    }

    @Override
    public void configure(JobConf jobConf) {

    }
}
